package minishell;

import java.io.*;

public class MiniShell implements Runnable {
	// loader
	public static void main(String[] args) {
		// setup environment
		Environment env = Environment.getInstance();
		env.setDirectory(new File("."));
		// start shell
		new MiniShell(System.in, System.out).run();
	}

	// =============================
	private BufferedReader reader = null;
	private PrintWriter writer = null;
	private Environment env = null;
	private CmdletHandler cmdletHandler = null;

	public MiniShell(InputStream in, OutputStream out) {
		super();
		this.reader = new BufferedReader(new InputStreamReader(in));
		this.writer = new PrintWriter(out, true);
		// CmdletHandler depends on writer
		this.cmdletHandler = new CmdletHandler(this.writer);
		this.env = Environment.getInstance();
	}

	public void run() {
		String input = "";
		while (false == env.isExit()) {
			while (0 == input.length())
				input = this.getInput();
			this.cmdletHandler.handle(input);
			input = "";
		}
	}

	/*
	 * �����Ƿ���input.trim()����ֱ�ӷ���input�أ�
	 */
	private String getInput() {
		try {
			String input = "";
			while (0 == input.length()) {
				System.out.print(this.getPrompt());
				input = reader.readLine();
			}
			return input;
		} catch (Exception e) {
			handleException(e);
			System.exit(0);
			return "";
		}

	}

	private String getPrompt() {
		return "msh>";
	}

	private void handleException(Exception e) {
		e.printStackTrace();
		System.out.println("�������ش����˳� ...");
	}
}
